"use strict";
const { Model } = require("sequelize");
const moment = require("moment/moment");
const { IdGenerator } = require("../utils/idGenerator");
moment.locale("zh-cn");

module.exports = (sequelize, DataTypes) => {
  class Course extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      // 关联模型 类似SQL left join
      models.Course.belongsTo(models.Category, {
        as: "category",
      });
      // 关联用户表
      models.Course.belongsTo(models.User, {
        as: "user",
      });
      // 每个章节有很多课程
      models.Course.hasMany(models.Chapter, {
        as: "chapters",
      });
      //多对多关联
      models.Course.belongsToMany(models.User, {
        through: models.Like,
        foreignKey: "courseId",
        as: "likeUsers",
      });
      //多对多关联
      models.Course.hasMany(models.Attachment, {
        foreignKey: "businessId",
        as: "attachmentList",
      });
    }
  }

  Course.init(
    {
      id: {
        type: DataTypes.INTEGER.UNSIGNED, // 无符号整数类型
        allowNull: false,
        primaryKey: true,
        defaultValue: function () {
          return IdGenerator.getNextID(); // 使用封装的ID生成方法
        },
      },
      categoryId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: "分类ID必须填写。" },
          notEmpty: { msg: "分类ID不能为空。" },
          async isPresent(value) {
            const category = await sequelize.models.Category.findByPk(value);
            if (!category) {
              throw new Error(`ID为:${value}的分类不存在。`);
            }
          },
        },
      },
      userId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: "用户ID必须填写。" },
          notEmpty: { msg: "用户ID不能为空。" },
          async isPresent(value) {
            const user = await sequelize.models.User.findByPk(value);
            if (!user) {
              throw new Error(`ID为:${value}的用户不存在。`);
            }
          },
        },
      },
      name: DataTypes.STRING,
      image: {
        type: DataTypes.STRING,
      },
      recommended: DataTypes.BOOLEAN,
      introductory: DataTypes.BOOLEAN,
      content: DataTypes.TEXT,
      likesCount: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
      },
      chaptersCount: DataTypes.INTEGER,
      createdAt: {
        type: DataTypes.DATE,
      },
      updatedAt: {
        type: DataTypes.DATE,
      },
    },
    {
      sequelize,
      modelName: "Course",
    },
  );
  return Course;
};
